package server

import (
	"github.com/akirakazu/go-simplejson"
)

// "publish" command handler
func (s *Server) onPublish(id string, m *Pack) {
	// Broadcast "CLIENT_PUBLISH" events
	publish := json.New()
	publish.Set("type", "CLIENT_PUBLISH")
	_msg, _ := m.Msg.Map()
	publish.Set("msg", _msg)
	s.iterateListeners(publish)

	if id != "" && !s.isProxyConn(id) {
		// Default response
		res := json.New()
		res.Set("msg", "ok")
		s.response(id, m, res)
	}

	if m.Msg.Has("isWan") {
		if id != "" {
			if s.proxy != nil && s.proxy.ready {
				s.proxy.sendPack(m)
			}
		}
		session_id, err := s.conns[id].identity.GetString("session_id")
		if err == nil {
			excludes := []string{}
			excludes = append(excludes, session_id)
			proxies := s.allProxies(excludes)
			for _, p := range proxies {
				s.send(p, m)
			}
		}
	}
}
